﻿using czj_shop.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace czj_shop.Models
{
    public class GoodService : IGoodService
    {
        private readonly czj_shopContext _db;
            /// <summary>
            /// 服务类构造函数
            /// </summary>
            /// <param name="db"></param>
        public GoodService(czj_shopContext db)
        {
            _db = db;
        }

        // 传入条件 和 分页数据
        /// <summary>
        /// 查询商品方法
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="cateId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<Good> GetGoods(string keyword, int cateId, int pageIndex, int pageSize)
        {
            var goodDb = _db.Goods.AsQueryable();

            if (!string.IsNullOrEmpty(keyword))
                goodDb = goodDb.Where(x => x.Name.Contains(keyword));

            if (cateId > 0)
                goodDb = goodDb.Where(x => x.Id == cateId);

            var goodList = goodDb
                .OrderByDescending(x => x.Id)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return goodList;
        }

        /// <summary>
        /// 獲取商品總數
        /// </summary>
        /// <returns></returns>
        public int GetGoodTotal(string keyword, int cateId)
        {
            var goodDb = _db.Goods.AsQueryable();

            if (!string.IsNullOrEmpty(keyword))
                goodDb = goodDb.Where(x => x.Name.Contains(keyword));

            if (cateId > 0)
                goodDb = goodDb.Where(x => x.Id == cateId);

            return goodDb.Count();
        }

    }
}
